﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Framework;
using Framework.Models;
using Koala.Framework;
using Koala.Framework.Caching;

namespace Koala.JiraTool.ScheduledTasks.Controls.Dialog
{
    public partial class AddTaskDialog : Form, ITransientDependency
    {
        #region Field

        private readonly ITaskController _taskController;
        private readonly ICacheManager _cacheManager;
        private readonly ISignals _signals;
        private readonly IList<TaskInfo> _taskInfos = new List<TaskInfo>();
        private string[] _taskTypes;

        #endregion Field

        #region Constructor

        public AddTaskDialog(ITaskController taskController, ICacheManager cacheManager, ISignals signals)
        {
            _taskController = taskController;
            _cacheManager = cacheManager;
            _signals = signals;
            InitializeComponent();
            dgvMain.AutoGenerateColumns = false;
        }

        #endregion Constructor

        #region Event

        private void dgvMain_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var row = dgvMain.Rows[e.RowIndex];
            var cell = row.Cells["cbcSelect"];
            if (e.ColumnIndex != cell.ColumnIndex)
                return;
            var keyword = row.Cells["Keyword"].Value.ToString();
            if ((bool)cell.EditedFormattedValue)
            {
                if (_taskInfos.Any(m => m.Keyword == keyword))
                    return;
                var list = dgvMain.DataSource as IList<TaskInfo>;
                var model = list.First(m => m.Keyword == row.Cells["Keyword"].Value.ToString());
                _taskInfos.Add(model);
            }
            else
            {
                var model = _taskInfos.FirstOrDefault(m => keyword == m.Keyword);
                if (model == null)
                    return;
                _taskInfos.Remove(model);
            }
        }

        private void tsbOk_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            Close();
        }

        private void tsbReset_Click(object sender, EventArgs e)
        {
            _signals.Trigger(Name + "TaskList.Change");
            AnsyDataBind(_taskTypes);
        }

        #endregion Event

        #region Publc Method

        public void LoadControl(params string[] taskTypes)
        {
            _taskTypes = taskTypes;
            Load += (s, e) =>
            {
                _taskInfos.Clear();
                AnsyDataBind(taskTypes);
            };
        }

        public IList<TaskInfo> GetList()
        {
            return _taskInfos;
        }

        #endregion Publc Method

        #region Private Method

        private void AnsyDataBind(params string[] taskTypes)
        {
            Text = "数据加载中...";
            toolStrip.Enabled = dgvMain.Enabled = false;
            var task = Task.Factory.StartNew(() => GetTaskList(taskTypes));
            task.ContinueWith(t =>
                {
                    Invoke(new Action(() =>
                        {
                            DataBind(t.Result);
                            Text = "添加任务 - 只显示(开启,处理中,重启)状态的任务，如列表与任务不匹配可手动刷新";
                            toolStrip.Enabled = dgvMain.Enabled = true;
                        }));
                });
        }

        private void DataBind(IList<TaskInfo> list)
        {
            dgvMain.DataSource = null;
            dgvMain.DataSource = list;
        }

        private IList<TaskInfo> GetTaskList(params string[] taskTypes)
        {
            return _cacheManager.Get(Name + "TaskList", ctx =>
            {
                ctx.Monitor(_signals.When(Name + "TaskList.Change"));
                return _taskController.GetTaskListByStatus(taskTypes);
            });
        }

        #endregion Private Method
    }
}